<?php

namespace App\Models;

use function foo\func;
use Illuminate\Database\Eloquent\Model;
use App\Repositories\QuizRepository;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;

class QuizItem extends Cachable
{
    protected $fillable = ['name', 'odds'];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function quiz()
    {
        return $this->belongsTo(Quiz::class);
    }

    /**
     * 当前用户下的注
     *
     * @return mixed
     */
    public function currentBets()
    {
        return $this->hasMany(Bet::class)
            ->where('user_id', request()->user()->id)
            ->whereIn('status', [
                QuizRepository::BET_STATUS_PROCESSED,
                QuizRepository::BET_STATUS_PROCESSING,
                QuizRepository::BET_STATUS_FINISHED
            ])
            ->whereNotNull('copper')
            ->select(['quiz_item_id', 'copper', 'odds', 'status', 'created_at'])
            ->orderBy('created_at', 'desc');
    }


    /**
     * 所有下注
     *
     * @return mixed
     */
    public function bets()
    {
        return $this->hasMany(Bet::class)
            ->whereIn('status', [
                QuizRepository::BET_STATUS_PROCESSED,
                QuizRepository::BET_STATUS_FINISHED
            ])
            ->whereNotNull('copper');
    }


    /**
     * @return mixed
     */
    public function processedBets()
    {
        return $this->hasMany(Bet::class)
            ->whereIn('status', [
                QuizRepository::BET_STATUS_PROCESSED,
            ])
            ->whereNotNull('copper');
    }


    /**
     * 下注统计
     *
     * @return array
     */
    public function getCachedCountAttribute()
    {
        return Cache::remember($this->cacheKey('count'), 15, function () {
			$players = $this->bets()->groupBy('user_id')->select('user_id')->get();
            return [
                'coppers' => (int)$this->bets()->sum('copper'),
                'players' => count($players),
            ];
        });
    }
}
